﻿using System.Windows;

namespace Orz.Framework.Foundation.Behaviors
{
    /// <summary>
    /// Real-time update the mouse position relative to the attached element.
    /// </summary>
    public class MousePositionBehavior : System.Windows.Interactivity.Behavior<UIElement>
    {
        #region DependencyProperty

        /// <summary>
        /// Gets or sets the X.
        /// </summary>
        /// <value>The X.</value>
        public double X
        {
            get { return (double)GetValue(XProperty); }
            set { SetValue(XProperty, value); }
        }

        // Using a DependencyProperty as the backing store for X.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty XProperty =
            DependencyProperty.Register("X", typeof(double), typeof(MousePositionBehavior), new UIPropertyMetadata());

        /// <summary>
        /// Gets or sets the Y.
        /// </summary>
        /// <value>The Y.</value>
        public double Y
        {
            get { return (double)GetValue(YProperty); }
            set { SetValue(YProperty, value); }
        }

        // Using a DependencyProperty as the backing store for Y.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty YProperty =
            DependencyProperty.Register("Y", typeof(double), typeof(MousePositionBehavior), new UIPropertyMetadata());

        #endregion

        #region Override

        protected override void OnAttached()
        {
            base.OnAttached();

            this.AssociatedObject.PreviewMouseMove += new System.Windows.Input.MouseEventHandler(AssociatedObject_PreviewMouseMove);
            this.AssociatedObject.PreviewDragOver += new DragEventHandler(AssociatedObject_PreviewDragOver);
        }

        protected override void OnDetaching()
        {
            base.OnDetaching();

            this.AssociatedObject.PreviewMouseMove -= new System.Windows.Input.MouseEventHandler(AssociatedObject_PreviewMouseMove);
            this.AssociatedObject.PreviewDragOver -= new DragEventHandler(AssociatedObject_PreviewDragOver);
        }

        #endregion

        #region Event handler

        void AssociatedObject_PreviewMouseMove(object sender, System.Windows.Input.MouseEventArgs e)
        {
            Point position = e.GetPosition(this.AssociatedObject);
            X = position.X;
            Y = position.Y;
        }

        void AssociatedObject_PreviewDragOver(object sender, DragEventArgs e)
        {
            Point position = e.GetPosition(this.AssociatedObject);
            X = position.X;
            Y = position.Y;
        }

        #endregion
    }
}
